<template>
<div class="container">
  <TopPart :isLogin="false" :isFunc="true" />
  <!-- 积分 -->
  <van-row gutter="20" class="topbar">
    <van-col span="12" class="number">
      {{ userInfo.points ? userInfo.points : 0 }} 积分
    </van-col>
    <!-- 待做：积分使用商城 -->
    <van-col span="12">
      <el-popover
        placement="left"
        trigger="hover">
        <div>该功能暂不开放，敬请期待~</div>
        <van-button slot="reference" round type="info" @click="usePoints" class="custom-btn">使用积分</van-button>
      </el-popover>
    </van-col>
  </van-row>

  <div class="center2-container">
    <calendar
      ref="calendar1"
      :value="value"
      :list="currDayList"
      @selectMonth="selectMonth"
      @selectYear="selectYear">
    </calendar>
  </div>

  <!-- 过去七天打卡 -->
  <div class="task-title">
      <span>当周打卡情况</span>
      <span style="color:#1989fa">{{currList.length > 0 ? '（打卡'+currList.length+'天）' : '（暂无打卡）'}}</span>
  </div> 
  
  <Steps :curr="currList" :dates="dateList" :range="rangeList" />
  <!-- 未打卡，一天只能打卡一次 -->
  <div v-if="!finishTask">
    <van-form style="margin:15px 10px" >
      <van-field label-width="9em" name="checkbox1" label="是否完成听写任务">
        <template #input>
          <van-checkbox v-model="task1" shape="square" />
        </template>
      </van-field>
      <van-field label-width="9em" name="checkbox2" label="是否发送练习视频">
        <template #input>
          <van-checkbox v-model="task2" shape="square" />
        </template>
      </van-field>
    </van-form>
    <!-- 上传听写图片，建议最多上传4张, 每张10M -->
    <div class="range">（上传你的听写图片，最多4张~）</div>
    <van-uploader 
      style="margin-top:15px"
      :after-read="afterRead" 
      v-model="imageList" 
      multiple 
      :max-count="4" 
      :max-size="1000 * 1024"
      @delete="afterDelete"
      @oversize="onOversize"
      @click-preview="clickPreview"
    />

    <div style="margin:15px 0;">
      <van-badge content="+1分">
        <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" @click="saveTask">
          一键打卡
        </van-button>
      </van-badge>
    </div>
  </div>
  <!-- 已打卡 -->
  <div v-else>
    <div class="notice-container">
      <div style="font-size: 14px;">太棒了，今天已成功打卡，明天再来吧~</div>
      <van-field label-width="9em" name="checkbox1" label="是否完成听写任务">
        <template #input>
          <van-checkbox v-model="finishWrite" shape="square" disabled />
        </template>
      </van-field>
      <van-field label-width="9em" name="checkbox2" label="是否发送练习视频">
        <template #input>
          <van-checkbox v-model="finishVideo" shape="square" disabled />
        </template>
      </van-field>
      <div class="image-wrapper">
        <van-image v-for="(item, index) in taskImages" :key="index" :src="item" @click="openPreview(index)">
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
    </div>
    <div style="margin-top:15px;">
      <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" @click="goBack">返回</van-button>
    </div>
    <!-- 图片预览 -->
    <van-image-preview v-model="showPreview" :images="taskImages" :startPosition="previewIndex" closable @change="onChange">
      <template v-slot:index>第{{ previewIndex+1 }}页</template>
    </van-image-preview>
  </div>
</div>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import TopPart from 'components/Home/TopPart'
import Steps from "components/Common/Steps"
import Calendar from 'components/Common/Calendar'
import { saveTaskB, getTaskB, getMonthTasksB, getWeekTasksB, addPointsB } from '@/api/task'
import { baseUrl, serverUrl } from '@/utils/setting'

export default {
    data() {
        return {
            task1: true,
            task2: true,
            // 一周打卡的日期
            currList: [],
            currDayList: [],
            // 一周的日期
            dateList: [],
            rangeList: [],
            stepList: ['1天', '2天', '3天', '4天', '5天', '6天', '7天'],
            imageList: [],
            // 上传的图片路径
            imagePath: [],
            finishTask: false,
            // 当日已打卡状态
            finishWrite: false,
            finishVideo: false,
            taskImages: [],
            // 默认日期(当日)
            value: [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()], 
            year: new Date().getFullYear(),
            month: new Date().getMonth() + 1,
            day: new Date().getDate(),
            timestamp: Date.now(),
            MIN_YEAR: 1891,
            MAX_YEAR: 2100,
            startDate: '',
            endDate: '',
            endDatePlus: '',
            // 图片预览
            showPreview: false,
            previewIndex: 1
        }
    },
    watch: {
        year (curVal, oldVal) {
            this.value = [this.year, this.month, this.day]
        }
    },
    computed: mapState([ 'userInfo' ]),
    created() {
        this.calculateWeek()
        this.checkTask()
        this.getMonthTasks()
        this.getWeekTasks()
    },
    methods: {
        selectMonth (month, year) {
            this.year = year
            this.month = month
        },
        selectYear (year) {
            this.year = year
        },
        // 计算当周周一到周日日期
        calculateWeek() {
            // 一天里一共的毫秒数
            let oneDayTime = 1000 * 60 * 60 * 24 
            let today = new Date()
            // 周日时，则强制赋值为7，否则为0
            let todayDay = today.getDay() || 7 
            let startDate = new Date(
                today.getTime() - oneDayTime * (todayDay - 1)
            )
            for(let i = 0; i < 7; i++){
                let temp = new Date(startDate.getTime() + i * oneDayTime)
                let year = temp.getFullYear()
                let month = temp.getMonth() + 1
                let day = temp.getDate()
                this.dateList[i] = `${month}`+'月'+`${day}`+'日'
                this.rangeList[i] = `${year}`+'-'+`${month}`+'-'+`${day}`
                if(i == 0) {
                  this.startDate = `${year}`+'-'+`${month}`+'-'+`${day}`
                }
                if(i == 6) {
                  this.endDate = `${year}`+'-'+`${month}`+'-'+`${day}`
                  // 当周截止日期要+1
                  let startPlus = new Date(startDate.getTime() + 7 * oneDayTime)
                  let dayPlus = startPlus.getDate()
                  this.endDatePlus = `${year}`+'-'+`${month}`+'-'+`${dayPlus}`
                }
            }
        },
        afterRead(file) {
            //正在上传
            file.status = 'uploading'
            file.message = '上传中...'
            let formData = new FormData()
            formData.append('file', file.file)
            let auth
            if (window.localStorage.getItem('token')) {
              auth = `Bearer ${localStorage.getItem('token')}`
            }
            //上传接口
            this.$axios.post(baseUrl+'task/uploadTask', formData, {
                headers: {
                    'Authorization': auth,
                    'content-type': 'multipart/form-data',
                }
            }).then(res => {
                if(res.data.code === '0') {
                    let path = serverUrl + res.data.filename.replace(/\\/g, '/')
                    this.imagePath.push(path)
                    file.status = 'done'
                    file.message = '上传成功'
                } else {
                    //上传后，失败
                    file.status = 'failed'
                    file.message = '上传失败'
                }
            }).catch(() => {
                //上传后，失败
                file.status = 'failed'
                file.message = '上传失败'
            })
        },
        afterDelete(file, detail) {
            this.imagePath.splice(detail.index, 1)
        },
        // 超过上传图片大小限制
        onOversize(file) {
            this.$toast.fail('图片不能超过10MB~')
        },
        // 打开预览提示关闭操作
        clickPreview() {
            this.$toast({
                message: '点击任意位置关闭',
                icon: 'like-o'
            })
        },
        // 查询该用户本月打卡
        getMonthTasks() {
            let data = {
                userId: this.userInfo.id,
                year: this.year,
                month: this.month,
                lastDay: new Date(this.year, this.month, 0).getDate()
            }
            getMonthTasksB(data).then(res => {
                if(res.data.code === '0') {
                  //已打卡(日期如：16)
                  this.currDayList = []
                  res.data.detail.forEach(item => {
                    this.currDayList.push(moment(item.created_at).format('DD'))
                  })
                } else {
                    this.$toast.fail(res.data.desc)
                }
            }).catch(res => {
                this.$toast.fail(res)
            })
        },
        // 查询该用户本周打卡
        getWeekTasks() {
            let data = {
                userId: this.userInfo.id,
                startDate: this.startDate,
                endDate: this.endDatePlus
            }
            getWeekTasksB(data).then(res => {
                if(res.data.code === '0') {
                    if(res.data.detail && res.data.detail.length > 0) {
                        //已打卡
                        this.currList = []
                        res.data.detail.forEach(item => {
                          item.created_at = moment(item.created_at).format('yyyy-MM-DD')
                          this.currList.push(item.created_at)
                        })
                    }
                    //this.$toast.success(res.data.desc)
                } else {
                    this.$toast.fail(res.data.desc)
                }
            }).catch(res => {
                this.$toast.fail(res)
            })
        },
        // 检查今日是否已打卡
        checkTask() {
            let data = {
                userId: this.userInfo.id 
            }
            getTaskB(data).then(res => {
                if(res.data.code === '0') {
                    if(res.data.detail && res.data.detail.length > 0) {
                        //已打卡
                        this.finishTask = true
                        let imgs = res.data.detail[0].task_images.split(',')
                        this.taskImages = imgs
                        // 今日的打卡图片
                        this.finishWrite = res.data.detail[0].finish_write
                        this.finishVideo = res.data.detail[0].finish_video
                    }
                    //this.$toast.success(res.data.desc)
                } else {
                    this.$toast.fail(res.data.desc)
                }
            }).catch(res => {
                this.$toast.fail(res)
            })
        },
        // 保存打卡信息
        saveTask() {
            if(this.imagePath.length === 0) {
                this.$toast({
                    message: '请上传听写图片~',
                    icon: 'like-o'
                })
                return
            }
            let data = {
                finishWrite: this.task1,
                finishVideo: this.task2,
                taskImages: this.imagePath.join(','),
                userId: this.userInfo.id
            }
            saveTaskB(data).then(res => {
                if(res.data.code === '0') {
                    this.$toast.success(res.data.desc)
                    //打卡成功后操作
                    this.addPoints()
                    this.checkTask()
                    this.getWeekTasks()
                    this.getMonthTasks()
                } else {
                    this.$toast.fail(res.data.desc)
                }
            }).catch(res => {
                this.$toast.fail(res)
            })
        },
        // 增加积分
        addPoints() {
            let data = {
                userId: this.userInfo.id,
                points: this.userInfo.points + 1
            }
            addPointsB(data).then(res => {
                if(res.data.code === '0') {
                    //this.$toast.success(res.data.desc)
                    this.userInfo.points += 1
                } else {
                    //this.$toast.fail(res.data.desc)
                }
            }).catch(res => {
                //this.$toast.fail(res.data.desc)
            })
        },
        // 返回用户页
        goBack() {
            this.$router.push({ name: 'User' })
        },
        onChange(index) {
            this.previewIndex = index
        },
        openPreview(index) {
            this.previewIndex = index
            this.showPreview = true
        },
        // 待做：使用积分页
        usePoints() {

        }
    },
    components: {
        TopPart,
        Steps,
        Calendar
    }
}
</script>

<style lang="stylus" scoped>
.container
    width 100%
    text-align center
    background-color #f5f5f5
    padding-bottom 100px
.task-title  
    margin-top 15px
.topbar
    margin 46px 10px 0px 10px
    padding 10px
    background-color #fefefe
    border-radius: 8px
.number
    font-size 20px
    line-height 44px
    font-weight 300
.range
    display flex
    font-size 14px
    color #a3a3a3
    justify-content center
.notice-container
    font-size 17px
    color #333
    margin 15px 10px 15px 10px
    padding 10px
    background-color #fefefe
    border-radius: 8px
.custom-btn 
    background-image linear-gradient(45deg, #0081ff, #1cbbb4)
    border-radius 10px
    padding 0 25px
    border none
.center2-container
    background #ddd
    margin 10px
.image-wrapper
    margin 10px 0
    padding 10px
</style>